import streamlit as st
import pandas as pd
import streamlit_authenticator as stauth
from authentication import save_config, load_config
from audit import log_audit, get_audit_logs
import re
from authentication import validate_username, get_next_user_id

def user_management_page():

    st.title("用户管理")

    # Create tabs
    tabs = st.tabs(["用户列表", "添加用户", "修改用户", "操作日志"])

    # 加载配置
    config = load_config()
    users = config["credentials"]["usernames"]

    # 用户列表 tab
    with tabs[0]:
        user_table = []
        for username, data in users.items():
            if isinstance(data.get("roles", ""), str):
                role = data.get("roles", "")
            else:
                role = ", ".join(data.get("roles", ""))

            display_status = "Suspended"
            if (data.get("status", "Active") == "Active" and
                data.get("failed_login_attempts", 0) <= config["system_settings"].get("max_login_attempts", 5)):
                display_status = "Active"

            user_table.append({
                "用户ID": data.get("user_id", "00000"),
                "用户名": username,
                "邮箱": data.get("email", ""),
                "角色": role,
                "状态": display_status
            })
        df = pd.DataFrame(user_table)
        st.dataframe(df, use_container_width=True)

    # 添加新用户 tab
    with tabs[1]:
        with st.form("add_user_form"):
            new_username = st.text_input("用户名（仅支持英文字母和数字）")
            new_email = st.text_input("邮箱")
            new_roles = st.multiselect(
                "角色",
                options=["user", "statusadmin", "calcadmin", "sysadmin"],
                placeholder="选择用户角色",
            )

            if st.form_submit_button("添加用户"):
                if not validate_username(new_username):
                    st.error("用户名只能包含英文字母和数字")
                elif new_username in users:
                    st.error("用户名已存在")
                elif not new_username:
                    st.error("用户名不能为空")
                else:
                    user_id = get_next_user_id(config)
                    hashed_password = stauth.Hasher.hash_passwords({'usernames': {new_username: {'password': 'abc123456'}}})['usernames'][new_username]['password']
                    users[new_username] = {
                        "user_id": user_id,
                        "email": new_email,
                        "password": hashed_password,
                        "roles": new_roles,
                        "status": "Active",
                        "name": "Placeholder",
                    }
                    save_config(config)
                    log_audit(
                        action="create_user",
                        username=st.session_state.username,
                        target_user_id=user_id,
                        details=f"Created user: {new_username}"
                    )
                    st.success(f"已添加用户: {new_username}，初始密码为: abc123456")
                    st.rerun()

    # 修改用户 tab
    with tabs[2]:
        edit_username = st.selectbox("选择要修改的用户", list(users.keys()))
        if edit_username:
            with st.form("edit_user_form"):
                edit_user = users[edit_username]
                new_email = st.text_input("邮箱", value=edit_user.get("email", ""))
                new_roles = st.multiselect(
                    "角色",
                    default=edit_user.get("roles", []),
                    options=["user", "statusadmin", "calcadmin", "sysadmin"],
                    placeholder="选择用户角色",
                )

                # 计算实际状态
                current_status = "Suspended"
                if (edit_user.get("status", "Active") == "Active" and
                    edit_user.get("failed_login_attempts", 0) <= config["system_settings"].get("max_login_attempts", 5)):
                    current_status = "Active"

                new_status = st.selectbox(
                    "状态",
                    options=["Active", "Suspended"],
                    index=0 if current_status == "Active" else 1
                )

                col1, col2 = st.columns(2)
                with col1:
                    submit = st.form_submit_button("保存修改")
                with col2:
                    reset_password = st.form_submit_button("重置密码")

                if submit:
                    changes = []
                    if new_email != edit_user.get("email", ""):
                        changes.append(f"email: {edit_user.get('email', '')} -> {new_email}")
                        edit_user["email"] = new_email

                    if new_roles != edit_user.get("roles", ""):
                        changes.append(f"roles: {edit_user.get('roles', '')} -> {new_roles}")
                        edit_user["roles"] = new_roles

                    if new_status != edit_user.get("status", "Active"):
                        changes.append(f"status: {edit_user.get('status', 'Active')} -> {new_status}")
                        edit_user["status"] = new_status
                        if new_status == "Active":
                            edit_user["failed_login_attempts"] = 0
                            changes.append("reset failed login attempts to 0")

                    save_config(config)
                    log_audit(
                        action="update_user",
                        username=st.session_state.username,
                        target_user_id=edit_user.get("user_id", "00000"),
                        details=f"Updated user {edit_username}: {'; '.join(changes)}"
                    )
                    st.success("用户信息已更新")
                    st.rerun()

                if reset_password:
                    hashed_password = stauth.Hasher.hash_passwords({'usernames': {edit_username: {'password': 'abc123456'}}})['usernames'][edit_username]['password']
                    edit_user["password"] = hashed_password
                    save_config(config)
                    log_audit(
                        action="reset_password",
                        username=st.session_state.username,
                        target_user_id=edit_user.get("user_id", "00000"),
                        details=f"Reset password for user: {edit_username}"
                    )
                    st.success("密码已重置为: abc123456")
                    st.rerun()

    # 操作日志 tab
    with tabs[3]:
        logs = get_audit_logs()
        if logs:
            log_df = pd.DataFrame(logs)
            st.dataframe(log_df, use_container_width=True)
        else:
            st.info("暂无操作记录")
